import React, { useState } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Checkbox, Form, Input, Flex, message } from 'antd';
// import { Button, Space } from 'antd-mobile'
import { Button } from 'antd';
import image from '../../image/image.png'
import styles from './css/l.module.css'
import instance from '../../api/request';
import JSEncrypt from 'jsencrypt';

// 公钥 - 使用您提供的公钥
const publicKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`;

// 加密方法 - 使用您提供的方法
const encryptedData = (publicKey, data) => {
    // 新建JSEncrypt对象
    const encryptor = new JSEncrypt();
    // 设置公钥
    encryptor.setPublicKey(publicKey); // publicKey为公钥
    // 加密数据
    return encryptor.encrypt(data); //data就是需要加密的密码
};

function login() {
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();

    const onFinish = (values) => {
        setLoading(true);

        // 准备登录数据
        const loginData = {
            email: values.email,
            pwd: values.pwd
        };

        // 密码加密 rsa - 使用您的方法
        loginData.pwd = encryptedData(publicKey, loginData.pwd);

        if (!loginData.pwd) {
            message.error('密码加密失败');
            setLoading(false);
            return;
        }

        console.log('发送的登录数据:', loginData);
        console.log('请求URL:', 'http://10.59.9.18:4999/health/user/v1/login');

        // 请求登录接口 - 使用您提供的路径
        instance.post('/health/user/v1/login', loginData).then(res => {
            console.log('登录响应:', res);

            const { status, result, message: responseMessage } = res.data;

            if (status === "0000") {
                message.success(responseMessage || '登录成功');
                // 这里可以添加登录成功后的跳转逻辑
                // 比如存储token到localStorage
                if (result && result.sessionId) {
                    localStorage.setItem('sessionId', result.sessionId);
                }
                if (result && result.userId) {
                    localStorage.setItem('userId', result.userId);
                }
                // 可以在这里添加路由跳转
                // window.location.href = '/dashboard';
            } else {
                message.error(responseMessage || '登录失败');
            }
        }).then(() => {
            setLoading(false);
        }).catch(error => {
            console.error('登录请求失败:', error);
            console.error('错误代码:', error.code);
            console.error('错误消息:', error.message);

            if (error.code === 'ERR_NETWORK') {
                message.error('网络连接失败，请检查服务器地址或网络连接');
            } else if (error.response) {
                message.error(`服务器错误: ${error.response.status} - ${error.response.statusText}`);
            } else {
                message.error('请求失败，请稍后重试');
            }
            setLoading(false);
        });
    };

    return (
        <div className={styles.box}>
            <img src={image} alt="" className={styles.tx} />

            <div >
                <Form
                    form={form}
                    className={styles.bd}
                    name="login"
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                >
                    <Form.Item
                        name="email"
                        rules={[
                            { required: true, message: '请输入邮箱!' },
                            { type: 'email', message: '请输入有效的邮箱格式!' }
                        ]}
                    >
                        <Input prefix={<UserOutlined />} placeholder="邮箱" />
                    </Form.Item>
                    <Form.Item
                        name="pwd"
                        rules={[{ required: true, message: '请输入密码!' }]}
                    >
                        <Input prefix={<LockOutlined />} type="password" placeholder="密码" />
                    </Form.Item>
                    <Form.Item>
                        <Flex justify="space-between" align="center">
                            <Form.Item name="remember" valuePropName="checked" noStyle>
                                <span style={{ color: '#ffffffad' }}>忘记密码</span>
                            </Form.Item>
                            <span style={{ color: '#ffffffad' }}>暂无账号？</span> <span style={{ color: '#fff' }}>立即注册</span>
                        </Flex>
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" loading={loading} style={{ width: '100%' }}>
                            {loading ? '登录中...' : '登录'}
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}

export default login